package com.alianzamedica.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.objectsearch.web.tools.Converter;

import com.alianzamedica.businessobject.Prescription;
import com.alianzamedica.businessobject.PrescriptionDetail;
import com.alianzamedica.view.PrescriptionDetailView;

/**
 * @author Carlos
 * 
 */
public class PrescriptionAddDetail extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession session = request.getSession();
		Prescription prescription = (Prescription) session
				.getAttribute("prescription");
		PrescriptionDetailView prescriptionDetailView = (PrescriptionDetailView) form;
		Integer drugId = Converter.string2Integer(prescriptionDetailView
				.getDrugId());
		Float quantity = Converter.string2Float(prescriptionDetailView
				.getQuantity());
		String observations = prescriptionDetailView.getObservaciones();
		Integer detailIndex = Converter.string2Integer(request
				.getParameter("arrayIndex"));
		PrescriptionDetail pDetail = new PrescriptionDetail();
		pDetail.setDrugId(drugId);
		pDetail.setQuantity(quantity);
		pDetail.setComments(observations);
		pDetail.setAdminInfo(prescriptionDetailView.getAdminInfo());
		String dose = prescriptionDetailView.getDose();
		String period = prescriptionDetailView.getPeriod();
		String administrationForm = prescriptionDetailView
				.getAdministrationForm();
		pDetail.setDose(dose);
		pDetail.setPeriod(period);
		pDetail.setAdministrationForm(administrationForm);

		if (prescription != null) {
			if (detailIndex == null) {
				prescription.detail.add(pDetail);
			} else {
				prescription.detail.set(detailIndex.intValue(), pDetail);
			}
		}
		return mapping.findForward("success");
	}

}
